package com.jydd.plug_in_study.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

/**
 * created by 韦敏敏
 * on 2019/12/27
 * LocalBroadcastManager工具类
 */
public class LBMUtils {
    private LBMUtils() {
        throw new RuntimeException("Do not need instantiate!");
    }
    public static LocalBroadcastManager getBroadcastManager(Context context){
        return LocalBroadcastManager.getInstance(context);
    }
    public static IntentFilter getIntentFilter(String ... actions){
        IntentFilter filter = null;
        if(actions.length > 0){
            filter = new IntentFilter();
            for(String action : actions){
                filter.addAction(action);
            }
        }
        return filter;
    }

    /**
     *  通过 Action注册广播接受者
     * @param context
     * @param receiver
     * @param actions
     */
    public static void registerReceiver(Context context, BroadcastReceiver receiver, String... actions){
        IntentFilter filter = getIntentFilter(actions);
        if(filter != null){
            registerReceiver(context, receiver, filter);
        }
    }

    /**
     *  通过intentFilter注册广播接受者
     * @param context
     * @param receiver
     * @param filter
     */
    public static void registerReceiver(Context context, BroadcastReceiver receiver, IntentFilter filter){
        getBroadcastManager(context).registerReceiver(receiver, filter);
    }

    /**
     * 注销广播接受者
     * @param context
     * @param receiver
     */
    public static void unRegisterReceiver(Context context, BroadcastReceiver receiver){
        getBroadcastManager(context).unregisterReceiver(receiver);
    }

    /**
     * 通过action发送广播
     * @param context
     * @param action
     */
    public static void sendBroadcast(Context context, String action){
        sendBroadcast(context, new Intent(action));
    }

    /**
     * 通过intent发送广播
     * @param context
     * @param intent
     */
    public static void sendBroadcast(Context context, Intent intent){
        getBroadcastManager(context).sendBroadcast(intent);
    }
    public static void sendBroadcastSync(Context context, String action){
        sendBroadcastSync(context, new Intent(action));
    }

    /**
     * 通过Intent同步发送广播
     * @param context
     * @param intent
     */
    public static void sendBroadcastSync(Context context, Intent intent){
        getBroadcastManager(context).sendBroadcastSync(intent);
    }
}
